package com.unicom.controller;

import com.unicom.model.Items;
import com.unicom.service.ItemsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@CrossOrigin
public class ItemsController {
	
	@Autowired
	private ItemsService service;


	@RequestMapping("/find")
	@ResponseBody
	public List<Items> findAllUsers(){
		return service.getall();
	}
	
	@RequestMapping("/find/{page}/{rows}")
	@ResponseBody
	public List<Items> findAllUsersPages(@PathVariable int page,@PathVariable int rows){
		return service.getall(page,rows);
	}
	
	@RequestMapping("/add")
	@ResponseBody
	public String addUser(){
		Items items = new Items();
		items.setName("111111");
		items.setPrice(10f);
		items.setDetail("11111");
		items.setCreatetime(new Date());
		service.add(items);
		return "ok";
	}
	
	@RequestMapping("/get")
	@ResponseBody
	public Items get(){
		return service.get(1);
	}

	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Map<String, Object> delete(@PathVariable int id) {
		HashMap<String, Object> map = new HashMap<>();

		try {
			service.delete(id);
			map.put("msg", "删除id:" + id + "成功！");
			map.put("code", 1);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "删除id:" + id + "失败:"+e.getMessage());
			map.put("code", 0);
		}
		return map;
	}

	@RequestMapping("/save")
	@ResponseBody
	public Map<String,Object> save(Items items){
		HashMap<String, Object> map = new HashMap<>();
		System.out.println(items);
		items.setCreatetime(new Date());
		try{
			service.add(items);
			map.put("msg", "新增成功！");
			map.put("code", 1);
			map.put("items", items);
		} catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "新增失败！"+e.getMessage());
			map.put("code", 0);
		}
		return map;
	}

	@RequestMapping("/update")
	@ResponseBody
	public Map<String,Object> update(Items items){
		HashMap<String, Object> map = new HashMap<>();
		System.out.println(items);
		try{
			service.update(items);
			Items items1 = service.get(items.getId());
			map.put("msg", "修改成功！");
			map.put("code", 1);
			map.put("items", items1);
		}catch (Exception e) {
			e.printStackTrace();
			map.put("msg", "修改失败！"+e.getMessage());
			map.put("code", 0);
		}
		return map;
	}


}
